from django.db import models
from django.utils import timezone

# Create your models here.

class UserBehavior(models.Model):
    """用户行为跟踪模型"""
    behavior_id = models.BigAutoField(primary_key=True)
    user_id = models.IntegerField(blank=True, null=True, help_text='用户ID，未登录用户为null')
    session_id = models.CharField(max_length=64, help_text='会话ID')
    action_type = models.CharField(max_length=50, help_text='行为类型，如view、click、search等')
    object_type = models.CharField(max_length=50, blank=True, null=True, help_text='对象类型，如product、category等')
    object_id = models.IntegerField(blank=True, null=True, help_text='对象ID')
    url = models.CharField(max_length=255, help_text='访问的URL')
    query = models.CharField(max_length=255, blank=True, null=True, help_text='搜索查询')
    user_agent = models.CharField(max_length=255, blank=True, null=True, help_text='用户代理')
    ip_address = models.CharField(max_length=64, blank=True, null=True, help_text='IP地址')
    create_time = models.DateTimeField(default=timezone.now, help_text='创建时间')

    class Meta:
        db_table = 'tb_user_behavior'
        verbose_name = '用户行为'
        verbose_name_plural = '用户行为'
        managed = False  # 表示表已存在，不需要Django创建
        indexes = [
            models.Index(fields=['user_id']),
            models.Index(fields=['action_type']),
            models.Index(fields=['create_time']),
            models.Index(fields=['object_type', 'object_id']),
        ]

    def __str__(self):
        return f"用户行为 {self.behavior_id}: {self.action_type}"
